

dpath = '/Users/landauland/Documents/Research/SabatiniLab/data/manuscriptPreparation/compileData';
f2resultsA = load(fullfile(dpath,'figure2resultsA'));
resA = f2resultsA.res;
NR = numel(resA);
distance = [resA(:).distance];


ptv = 0.1:0.1:1000;
pglu = cell2mat({resA(:).pglu});
pap = cell2mat({resA(:).pap});

tvec = 1:512;
sap = cell2mat({resA(:).sap});
sglu = cell2mat({resA(:).sglu});
sgap = cell2mat({resA(:).sgap});
ssyn = cell2mat({resA(:).ssyn});
spk = cell2mat({resA(:).spk}');
sbase = cell2mat({resA(:).sbase}'); % spine Base

dap = cell2mat({resA(:).dap});
dglu = cell2mat({resA(:).dglu});
dgap = cell2mat({resA(:).dgap});
dpk = cell2mat({resA(:).dpk}');
dbase = cell2mat({resA(:).dbase}');

minAllowed = 0.001;
spk(spk < minAllowed) = minAllowed;
dpk(dpk < minAllowed) = minAllowed;

% amplification trace
sapbase = sap - sbase(:,1)';
sglubase = sglu - sbase(:,2)';
sgapbase = sgap - sbase(:,3)';

% dendrite amplification trace 
dapbase = dap - dbase(:,1)';
dglubase = dglu - dbase(:,2)';
dgapbase = dgap - dbase(:,3)';

% Added the following section on 211102 to make the peak detection better
filterDepth = 5;
pkSum = -2:7;
pkWindow = find(tvec>=100, 1):find(tvec>=150,1);
dpkNew = size(dpk);
spkNew = size(spk);
for nr = 1:NR
    % Recompute peaks for spines
    [~,cidx] = max(medfilt1(sapbase(pkWindow,nr),filterDepth));
    cidx = cidx + pkWindow(1);
    spkNew(nr,1) = mean(sapbase(cidx + pkSum,nr));
    
    [~,cidx] = max(medfilt1(sglubase(pkWindow,nr),filterDepth));
    cidx = cidx + pkWindow(1);
    spkNew(nr,2) = mean(sglubase(cidx + pkSum,nr));
    
    [~,cidx] = max(medfilt1(sgapbase(pkWindow,nr),filterDepth));
    cidx = cidx + pkWindow(1);
    spkNew(nr,3) = mean(sgapbase(cidx + pkSum,nr));
    
    % Recompute peaks for dendrites
    [~,cidx] = max(medfilt1(dapbase(pkWindow,nr),filterDepth));
    cidx = cidx + pkWindow(1);
    dpkNew(nr,1) = mean(dapbase(cidx + pkSum,nr));
    
    [~,cidx] = max(medfilt1(dglubase(pkWindow,nr),filterDepth));
    cidx = cidx + pkWindow(1);
    dpkNew(nr,2) = mean(dglubase(cidx + pkSum,nr));
    
    [~,cidx] = max(medfilt1(dgapbase(pkWindow,nr),filterDepth));
    cidx = cidx + pkWindow(1);
    dpkNew(nr,3) = mean(dgapbase(cidx + pkSum,nr));
end

% calculate peak for synthetic
bswin = [80 98];
pwsyn = [100 150];
pklength=20;
synpk = zeros(NR,1);
synpkNew = zeros(NR,1);
synpkidx = zeros(NR,1);
for s = 1:NR
    [~,synpkidx(s)] = max(medfilt1(ssyn(pwsyn(1):pwsyn(2),s),filterDepth)); % Updated on 211102 in accordance with earlier comment
    synpkidx(s) = synpkidx(s) + pwsyn(1) - 1;
    synpk(s) = mean(ssyn((0:pklength-1)+synpkidx(s),s));
    synpkNew(s) = mean(ssyn(synpkidx(s)+pkSum,s));
end
synbase = mean(ssyn(bswin,:),1)';
synpk = synpk - synbase;
synpkNew = synpkNew - synbase;

useSynPk = synpkNew; % Updated this so I can use the new peak detection method 
ampreglu = (spk(:,3)-useSynPk)./abs(spk(:,2)); % (amplification - synthetic)/gluAlone
nlComponent = spk(:,3) - useSynPk;
exToPlot = (spk(:,1)<0.05) & (ampreglu>0.5);
ampreglu(ampreglu<0) = 0;

nlComponent(nlComponent<minAllowed) = minAllowed;

syntrace = sglubase + nanshift(sapbase,5,0);
amptrace = sgapbase - syntrace;
ampretrace = sgapbase ./ useSynPk';

dsyntrace = dglubase + nanshift(dapbase,5,0);
dsynpk = zeros(NR,1);
[~,dsynpkidx] = max(dsyntrace(105:150,:),[],1);
dsynpkidx = dsynpkidx + 105 - 1;
for s = 1:NR
    dsynpk(s) = mean(dsyntrace(dsynpkidx(s):dsynpkidx(s)+pklength-1,s),1);
end    

damptrace = dgapbase - dsyntrace;
dampretrace = dgapbase ./ dsynpk';

figure2resB = load(fullfile(dpath,'figure2resultsB'));
resB = figure2resB.f1res;

% Get f1 distance
f1distance = [resB(:).distance];
f1distidx = (f1distance > 0); % some weren't calculated
f1distance = f1distance(f1distidx);

% Get f1 dendrite AP Peak Calcium 
f1dpk = [resB(f1distidx).dpk];
f1dpk(f1dpk<minAllowed)=minAllowed; % make sure they are not below 0 which is an artifact of noise

% Get f1 spine AP-peak Calcium 
f1spk = {resB(f1distidx).spk};
f1spkIdx = 1:length(f1spk);
f1spkFullIdx = cell2mat(cellfun(@(idx,N) idx*ones(1,length(N)), num2cell(f1spkIdx), f1spk, 'uni', 0));

% Create list of cell IDs after accounting for structure fields with
% multiple ROIs
f1date = {resB(f1distidx).date};
f1id = {resB(f1distidx).cellid};
f1date = f1date(f1spkFullIdx);
f1id = f1id(f1spkFullIdx);
f1cellID = cellfun(@(date,id) [num2str(date),id],f1date,f1id,'uni',0);
[f1ucid,~,f1cellidx] = unique(f1cellID);

% Get all of them! (some are NaNs)
f1spkFull = cell2mat(f1spk);
f1spkFull(f1spkFull<minAllowed) = minAllowed;
f1spkDistance = f1distance(f1spkFullIdx);
f1dpkSpkCompare = f1dpk(f1spkFullIdx);
f1spk = {resB(f1distidx).spk};



% Get pairs to do same recording comparison
idxPairs = cellfun(@(c) length(c)==2, f1spk, 'uni', 1);
distPairs = f1spkDistance(idxPairs);
spkPairs = f1spk(idxPairs);
pairs12 = cell2mat(cellfun(@(c) c([1,2]), spkPairs, 'uni', 0)');


% Properties 
colWidCM = [85, 114, 174]/10; % in mm
% Axes Size
axAspectRatio = 10.5/13;
axWidth = colWidCM(2)/7 * [2,3]; % Left two columns are 2x, right is 3x
axHeight = 3.35; %colWidCM(3)/4 * (10.5/13);

% Markup properties (smaller for insets!)
fontSize = 7;
lineWidth = 0.5;
markerSize = 4;




%% -- Figure 2 --


% Figure 2A
rng(3) % The PMTs were closed during the uncaging pulse
sglubase(99:101,:) = std(sglubase(60:98,:),[],1) .* randn(3,NR);
sgapbase(99:101,:) = std(sgapbase(60:98,:),[],1) .* randn(3,NR);
rng('default');

exspine = 25;
yLimGluBase = [-0.05 1.2*max(sglubase(:))];
yLim = [-0.05 0.875];
tvIdx = find(tvec>=80,1):find(tvec>=350,1);
tvUse = tvec(tvIdx);
xSchematic = 42 + 9*[0,1,3,2];
linearSumSignal = sglubase + nanshift(sapbase,5);

figure(1); clf; hold on;
set(gcf,'units','centimeters','position',[40 30 axWidth(1) axHeight]);
set(gca,'units','centimeters','position',[0.15 0.08 axWidth(1)*0.9 axHeight]);
plot(tvUse,sapbase(tvIdx,exspine),'color','k','linewidth',lineWidth);
plot(tvUse,sglubase(tvIdx,exspine),'color','r','linewidth',lineWidth);
plot(tvUse,sgapbase(tvIdx,exspine),'color',[1,0.55,0],'linewidth',lineWidth);
line(xSchematic(3)+[0,0],[spk(exspine,1)+spk(exspine,2), spk(exspine,3)],'color','b','linewidth',lineWidth);
line([0 350],[0 0],'color','k','linewidth',lineWidth/2,'linestyle','--');
plot(tvUse,sapbase(tvIdx,exspine),'color','k','linewidth',lineWidth);
plot(tvUse,sglubase(tvIdx,exspine),'color','r','linewidth',lineWidth);
plot(tvUse,sgapbase(tvIdx,exspine),'color',[1,0.55,0],'linewidth',lineWidth);
plot(tvUse,linearSumSignal(tvIdx,exspine),'color','k','linewidth',lineWidth);
plot(tvUse,linearSumSignal(tvIdx,exspine),'color','r','linewidth',lineWidth);
xlim([32 350]);
ylim([-0.055 yLim(2)]);
% Plot Schematic of Amplification Calculation
usePeak = spkNew;
line(xSchematic(1)+[0,0],[0 usePeak(exspine,1)],'color','k','linewidth',lineWidth*2);
line(xSchematic(2)+[0,0],[0 usePeak(exspine,2)],'color','r','linewidth',lineWidth*2);
line(xSchematic(3)+[0,0],[0 usePeak(exspine,1)],'color','k','linewidth',lineWidth*2);
line(xSchematic(3)+[0,0],[usePeak(exspine,1) usePeak(exspine,1)+usePeak(exspine,2)],'color','r','linewidth',lineWidth*2);
line(xSchematic(3)+[0,0],[usePeak(exspine,1)+usePeak(exspine,2), usePeak(exspine,3)],'color','b','linewidth',lineWidth*2);
line(xSchematic(4)+[0,0],[0 usePeak(exspine,3)],'color',[1,0.55,0],'linewidth',lineWidth*2);
plot(xSchematic(1),usePeak(exspine,1),'color','k','marker','o','markerfacecolor','k','markersize',markerSize-1);
plot(xSchematic(2),usePeak(exspine,2),'color','r','marker','o','markerfacecolor','r','markersize',markerSize-1);
plot(xSchematic(3),sum(usePeak(exspine,[1,2])),'color','r','marker','o','markerfacecolor','r','markersize',markerSize-1);
plot(xSchematic(3),usePeak(exspine,1),'color','k','marker','o','markerfacecolor','k','markersize',markerSize-1);
plot(xSchematic(3),usePeak(exspine,3),'color','b','marker','o','markerfacecolor','b','markersize',markerSize-1);
plot(xSchematic(4),usePeak(exspine,3),'color',[1,0.55,0],'marker','o','markerfacecolor',[1,0.55,0],'markersize',markerSize-1);
% Indicate time of stimulation
line([100 100],[-0.055 -0.0375],'color','k','linewidth',lineWidth);
% Scale Bar
scalePosition = [225 0.40 30 0.04];
line(scalePosition(1)+[0 scalePosition(3)],scalePosition(2)*[1,1],'linewidth',lineWidth,'color','k');
line(scalePosition(1)*[1,1],scalePosition(2)+[0 scalePosition(4)],'linewidth',lineWidth,'color','k');
text(scalePosition(1),scalePosition(2),'30 ms','Fontsize',fontSize,'HorizontalAlignment','Left','VerticalAlignment','Top');
text(scalePosition(1),scalePosition(2),'4% \DeltaG/R','Fontsize',fontSize,'HorizontalAlignment','Left','VerticalAlignment','Bottom','Rotation',90);
% Plot Legend
legPos = [328, 348, yLim(2)-0.11,-yLim(2)*0.08, -5];
line(legPos([1,2]),(legPos(3)+0*legPos(4))*[1,1],'Color','b','linewidth',lineWidth);
line(legPos([1,2]),(legPos(3)+1*legPos(4))*[1,1],'Color','k','linewidth',lineWidth);
line(legPos([1,2]),(legPos(3)+2*legPos(4))*[1,1],'Color','r','linewidth',lineWidth);
line(legPos([1,2]),(legPos(3)+3*legPos(4))*[1,1],'Color',[1,0.55,0],'linewidth',lineWidth);
line(legPos([1,2]),(legPos(3)+4*legPos(4))*[1,1],'Color','r','linewidth',lineWidth);
line(legPos([1,2]),(legPos(3)+4*legPos(4))*[1,1],'Color','k','linewidth',lineWidth,'linestyle','--');
text(legPos(1)+legPos(5),legPos(3)+0*legPos(4)+0.01,'\DeltaCa_{amp}','Fontsize',fontSize,'HorizontalAlignment','Right');
text(legPos(1)+legPos(5),legPos(3)+1*legPos(4),'1 AP','Fontsize',fontSize,'HorizontalAlignment','Right');
text(legPos(1)+legPos(5),legPos(3)+2*legPos(4),'uEPSP','Fontsize',fontSize,'HorizontalAlignment','Right');
text(legPos(1)+legPos(5),legPos(3)+3*legPos(4),'Pairing','Fontsize',fontSize,'HorizontalAlignment','Right');
text(legPos(1)+legPos(5),legPos(3)+4*legPos(4),'sum','Fontsize',fontSize,'HorizontalAlignment','Right');
set(gca,'visible','off');



% Figure 2B
setBackX = [-0.025 -0.038 -0.035 -0.09];
setBackY = [-0.025 -0.038 -0.045 -0.195];
figure(2); clf; hold on;
set(gcf,'units','centimeters','position',[40 20 axWidth(1) axHeight]);
set(gca,'units','centimeters','position',[0.75 0.75 axWidth(1)*0.75 axWidth(1)*0.75]); % Note difference for equal axes!
patch([0 0.04 0.04 0],[0 0 0.5 0.5],[0.5 0.5 1],'EdgeColor','none');
patch([0.1 0.3 0.3 0.1],[0 0 0.5 0.5],[0.5 0.5 0.5],'EdgeColor','none');
plot(spk(:,1),nlComponent,'linestyle','none','marker','.','markersize',markerSize,'color','k');
axis('equal')
line([0 0.5],setBackY(1)*[1,1],'color','k','linewidth',lineWidth);
line(setBackX(1)*[1,1],[0 0.5],'color','k','linewidth',lineWidth);
ticks = 0:0.2:0.4;
for t = ticks
    line(t+[0,0],setBackX([1 2]),'color','k','linewidth',lineWidth);
    text(t,setBackX(3),num2str(t),'fontsize',fontSize,'horizontalalignment','center','verticalAlignment','top');
    line(setBackY([1 2]),t+[0,0],'color','k','linewidth',lineWidth);
    text(setBackY(3),t,num2str(t),'fontsize',fontSize,'horizontalalignment','right','verticalAlignment','Middle');
end
xlim([setBackY(2) 0.5]);
ylim([setBackX(2) 0.5]);
text(0.25,setBackX(4),'\DeltaCa_{AP} (\DeltaG/R)','fontsize',fontSize,'HorizontalAlignment','center','verticalAlignment','top');
text(setBackY(4),0.25,'Amplification (\DeltaG/R)','fontsize',fontSize,'HorizontalAlignment','center','verticalAlignment','top','Rotation',90);
set(gca,'visible','off');



% Figure 2C 
idxSilent = dpk(:,1) <= 0.04; 
idxActive = (dpk(:,1) >= 0.1) & (dpk(:,1) <= 0.3); 
xShow = 50:400; 
stdcor = [sqrt(sum(idxSilent)), sqrt(sum(idxActive))]; 
figure(3); clf; hold on;
set(gcf,'units','centimeters','position',[44 30 axWidth(1) axHeight]);
set(gca,'units','centimeters','position',[0.15 0.08 axWidth(1)*0.9 axHeight]);
% plot spine traces - 1AP
shadedErrorBar(xShow, mean(sapbase(xShow,idxActive),2), std(sapbase(xShow,idxActive),1,2)/stdcor(2), {'color','k','linewidth',lineWidth},0);
shadedErrorBar(xShow, mean(sapbase(xShow,idxSilent),2), std(sapbase(xShow,idxSilent),1,2)/stdcor(1), {'color','b','linewidth',lineWidth},0);
% Axis Limits
xlim([45 400]);
ylim([-0.03 0.27]);
% Plot tick to indicate time of stimulations
line([100 100],[-0.03 -0.019],'color','k','linewidth',lineWidth);
% Scale Bar
scalePosition = [315 0.085 40 0.03];
line(scalePosition(1)+[0 scalePosition(3)],scalePosition(2)*[1,1],'linewidth',lineWidth,'color','k');
line(scalePosition(1)*[1,1],scalePosition(2)+[0 scalePosition(4)],'linewidth',lineWidth,'color','k');
text(scalePosition(1),scalePosition(2),sprintf('%d ms',scalePosition(3)),'Fontsize',fontSize,'HorizontalAlignment','Left','VerticalAlignment','Top');
text(scalePosition(1),scalePosition(2),[sprintf('%d%%',100*scalePosition(4)),' \DeltaG/R'],'Fontsize',fontSize,'HorizontalAlignment','Left','VerticalAlignment','Bottom','Rotation',90);
% Label Traces w/ Schematic
spineSchematic = [80 -17.5 0.031 0.0125];
line(spineSchematic([1,1]),spineSchematic(3)+spineSchematic(4)*[-1,1],'color','k','linewidth',lineWidth*4);
line(spineSchematic(1)+[0 spineSchematic(2)],spineSchematic(3)*[1,1],'color','k','linewidth',lineWidth*3);
plot(spineSchematic(1)+spineSchematic(2),spineSchematic(3),'marker','.','markersize',markerSize*2.5,'color','k');
plot(spineSchematic(1)+spineSchematic(2),spineSchematic(3),'marker','.','markersize',markerSize*2,'color','r');
% Labels -- top right
text(55, 0.235, '\DeltaCa_{AP}', 'Fontsize',fontSize,'horizontalAlignment','Left')
set(gca,'visible','off');



% Figure 2E
figure(4); clf; hold on;
set(gcf,'units','centimeters','position',[48 30 axWidth(1) axHeight]);
set(gca,'units','centimeters','position',[0.15 0.08 axWidth(1)*0.9 axHeight]);
% plot dendritic traces - 1AP
shadedErrorBar(xShow, mean(medfilt1(dapbase(xShow,idxActive),5),2), std(dapbase(xShow,idxActive),1,2)/stdcor(2), {'color','k','linewidth',lineWidth},0);
shadedErrorBar(xShow, mean(medfilt1(dapbase(xShow,idxSilent),5),2), std(dapbase(xShow,idxSilent),1,2)/stdcor(1), {'color','b','linewidth',lineWidth},0);
% Axis Limits
xlim([45 400]);
ylim([-0.03 0.27]);
% Plot tick to indicate time of stimulations
line([100 100],[-0.03 -0.019],'color','k','linewidth',lineWidth);
% Scale Bar
scalePosition = [315 0.085 40 0.03];
line(scalePosition(1)+[0 scalePosition(3)],scalePosition(2)*[1,1],'linewidth',lineWidth,'color','k');
line(scalePosition(1)*[1,1],scalePosition(2)+[0 scalePosition(4)],'linewidth',lineWidth,'color','k');
text(scalePosition(1),scalePosition(2),sprintf('%d ms',scalePosition(3)),'Fontsize',fontSize,'HorizontalAlignment','Left','VerticalAlignment','Top');
text(scalePosition(1),scalePosition(2),[sprintf('%d%%',100*scalePosition(4)),' \DeltaG/R'],'Fontsize',fontSize,'HorizontalAlignment','Left','VerticalAlignment','Bottom','Rotation',90);
% Label Traces w/ Schematic
dendriteSchematic = [70 17.5 0.031 0.005];
line(dendriteSchematic([1,1]),dendriteSchematic(3)+3*dendriteSchematic(4)*[-1,1],'color','k','linewidth',lineWidth*4);
line(dendriteSchematic(1)-[0 dendriteSchematic(2)],(dendriteSchematic(3)-dendriteSchematic(4))*[1,1],'color','k','linewidth',lineWidth*3);
line(dendriteSchematic(1)+[0 dendriteSchematic(2)],(dendriteSchematic(3)+dendriteSchematic(4))*[1,1],'color','k','linewidth',lineWidth*3);
plot(dendriteSchematic(1)-dendriteSchematic(2),dendriteSchematic(3)-dendriteSchematic(4),'marker','.','markersize',markerSize*2.5,'color','k');
plot(dendriteSchematic(1)+dendriteSchematic(2),dendriteSchematic(3)+dendriteSchematic(4),'marker','.','markersize',markerSize*2.5,'color','k');
line(dendriteSchematic([1,1]),dendriteSchematic(3)+3*dendriteSchematic(4)*[-1,1],'color','r','linewidth',lineWidth*2.5);
% Label High/Low 
legPos = [400 0.235 -20 -10 -0.025];
line(legPos(1)+[0 legPos(3)],legPos(2)*[1,1],'lineWidth',lineWidth,'color','k');
line(legPos(1)+[0 legPos(3)],(legPos(2)+legPos(5))*[1,1],'lineWidth',lineWidth,'color','b');
text(sum(legPos([1 3 4])),legPos(2),'High \DeltaCa_{AP}','fontsize',fontSize,'horizontalAlignment','right');
text(sum(legPos([1 3 4])),legPos(2)+legPos(5),'Low \DeltaCa_{AP}','fontsize',fontSize,'horizontalAlignment','right');
set(gca,'visible','off');



% Figure 2D
figure(5); clf; hold on;
set(gcf,'units','centimeters','position',[44 20 axWidth(1) axHeight]);
set(gca,'units','centimeters','position',[0.15 0.08 axWidth(1)*0.9 axHeight]);
% plot spine traces - amplification
shadedErrorBar(xShow, mean(amptrace(xShow,idxActive),2), std(amptrace(xShow,idxActive),1,2)/stdcor(2), {'color','k','linewidth',lineWidth},0);
shadedErrorBar(xShow, mean(amptrace(xShow,idxSilent),2), std(amptrace(xShow,idxSilent),1,2)/stdcor(1), {'color','b','linewidth',lineWidth},0);
% Axis Limits
xlim([45 400]);
ylim([-0.03 0.305]);
% Plot tick to indicate time of stimulations
line([100 100],[-0.03 -0.019],'color','k','linewidth',lineWidth);
% Scale Bar
scalePosition = [315 0.085 40 0.03];
line(scalePosition(1)+[0 scalePosition(3)],scalePosition(2)*[1,1],'linewidth',lineWidth,'color','k');
line(scalePosition(1)*[1,1],scalePosition(2)+[0 scalePosition(4)],'linewidth',lineWidth,'color','k');
text(scalePosition(1),scalePosition(2),sprintf('%d ms',scalePosition(3)),'Fontsize',fontSize,'HorizontalAlignment','Left','VerticalAlignment','Top');
text(scalePosition(1),scalePosition(2),[sprintf('%d%%',100*scalePosition(4)),' \DeltaG/R'],'Fontsize',fontSize,'HorizontalAlignment','Left','VerticalAlignment','Bottom','Rotation',90);
% Label Traces w/ Schematic
spineSchematic = [80 -17.5 0.031 0.0125];
line(spineSchematic([1,1]),spineSchematic(3)+spineSchematic(4)*[-1,1],'color','k','linewidth',lineWidth*4);
line(spineSchematic(1)+[0 spineSchematic(2)],spineSchematic(3)*[1,1],'color','k','linewidth',lineWidth*3);
plot(spineSchematic(1)+spineSchematic(2),spineSchematic(3),'marker','.','markersize',markerSize*2.5,'color','k');
plot(spineSchematic(1)+spineSchematic(2),spineSchematic(3),'marker','.','markersize',markerSize*2,'color','r');
% Labels -- top right
text(55, 0.2725, 'Amplification', 'Fontsize',fontSize,'horizontalAlignment','left')
set(gca,'visible','off');


% Figure 2F
figure(6); clf; hold on;
set(gcf,'units','centimeters','position',[48 20 axWidth(1) axHeight]);
set(gca,'units','centimeters','position',[0.15 0.08 axWidth(1)*0.9 axHeight]);
% plot dendritic traces - 1AP
shadedErrorBar(xShow, mean(medfilt1(damptrace(xShow,idxActive),5),2), std(damptrace(xShow,idxActive),1,2)/stdcor(2), {'color','k','linewidth',lineWidth},0);
shadedErrorBar(xShow, mean(medfilt1(damptrace(xShow,idxSilent),5),2), std(damptrace(xShow,idxSilent),1,2)/stdcor(1), {'color','b','linewidth',lineWidth},0);
% Axis Limits
xlim([45 400]);
ylim([-0.03 0.305]);
% Plot tick to indicate time of stimulations
line([100 100],[-0.03 -0.019],'color','k','linewidth',lineWidth);
% Scale Bar
scalePosition = [315 0.085 40 0.03];
line(scalePosition(1)+[0 scalePosition(3)],scalePosition(2)*[1,1],'linewidth',lineWidth,'color','k');
line(scalePosition(1)*[1,1],scalePosition(2)+[0 scalePosition(4)],'linewidth',lineWidth,'color','k');
text(scalePosition(1),scalePosition(2),sprintf('%d ms',scalePosition(3)),'Fontsize',fontSize,'HorizontalAlignment','Left','VerticalAlignment','Top');
text(scalePosition(1),scalePosition(2),[sprintf('%d%%',100*scalePosition(4)),' \DeltaG/R'],'Fontsize',fontSize,'HorizontalAlignment','Left','VerticalAlignment','Bottom','Rotation',90);
% Label Traces w/ Schematic
dendriteSchematic = [70 17.5 0.031 0.005];
dendriteSchematic([3,4]) = dendriteSchematic([3,4])*(0.305 - -0.03)/(0.27 - -0.03);
line(dendriteSchematic([1,1]),dendriteSchematic(3)+3*dendriteSchematic(4)*[-1,1],'color','k','linewidth',lineWidth*4);
line(dendriteSchematic(1)-[0 dendriteSchematic(2)],(dendriteSchematic(3)-dendriteSchematic(4))*[1,1],'color','k','linewidth',lineWidth*3);
line(dendriteSchematic(1)+[0 dendriteSchematic(2)],(dendriteSchematic(3)+dendriteSchematic(4))*[1,1],'color','k','linewidth',lineWidth*3);
plot(dendriteSchematic(1)-dendriteSchematic(2),dendriteSchematic(3)-dendriteSchematic(4),'marker','.','markersize',markerSize*2.5,'color','k');
plot(dendriteSchematic(1)+dendriteSchematic(2),dendriteSchematic(3)+dendriteSchematic(4),'marker','.','markersize',markerSize*2.5,'color','k');
line(dendriteSchematic([1,1]),dendriteSchematic(3)+3*dendriteSchematic(4)*[-1,1],'color','r','linewidth',lineWidth*2.5);
set(gca,'visible','off');


% Figure 2G
setBackX = [-0.015 -0.025 -0.025 -0.068];
setBackY = [-5 -10 -12 -40];
figure(7); clf; 
set(gcf,'units','centimeters','position',[52 30 axWidth(2) axHeight]);
set(gca,'units','centimeters','position',[0.825 0.6 axWidth(2)*0.76 axHeight*0.82]);
plot(f1spkDistance, f1spkFull, 'marker','.','color','k','markersize',markerSize,'linestyle','none');
xlim([setBackY(2) 300]);
ylim([setBackX(2) 0.5]);
line([0 300],setBackX(1)+[0,0],'color','k','linewidth',lineWidth);
line(setBackY(1)+[0 0],[0 0.5],'color','k','linewidth',lineWidth);
xticks = 0:100:300;
for xt = xticks
    line(xt+[0,0],setBackX([1 2]),'color','k','linewidth',lineWidth);
    text(xt,setBackX(3),num2str(xt),'fontsize',fontSize,'horizontalalignment','center','verticalAlignment','top');
end
text(150,setBackX(4),'distance from soma (µm)','Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Top');
yticks = 0:0.2:0.4;
for yt = yticks
    line(setBackY([1,2]),yt+[0,0],'color','k','linewidth',lineWidth);
    text(setBackY(3),yt,num2str(yt),'fontsize',fontSize,'horizontalalignment','right');
end
text(setBackY(4),0.25,'\DeltaCa_{AP} (\DeltaG/R)','fontsize',fontSize,'HorizontalAlignment','center','verticalAlignment','bottom','Rotation',90);
set(gca,'visible','off');



% Figure 2H
setBackX = [-0.015 -0.025 -0.025 -0.056];
setBackY = [-0.015 -0.025 -0.025 -0.066];
figure(8); clf; hold on;
set(gcf,'units','centimeters','position',[52 20 axWidth(2) axHeight]);
set(gca,'units','centimeters','position',[0.8 0.64 axWidth(2)*0.76 axHeight*0.8]);
distanceRange = (f1spkDistance' >= 100);% & (f1spkDistance' <= 200);
distThreshold = 21; 
sortByDistYesPeakNo = false;
for ucid = 1:length(f1ucid)
    cidx = find(f1cellidx==ucid & distanceRange);
    if length(cidx)<2, continue, end
    cDistance = f1spkDistance(cidx);
    if sortByDistYesPeakNo
        [~,cSortIdx] = sort(cDistance);
    else
        [~,cSortIdx] = sort(f1spkFull(cidx),'descend');
    end
    cDistance = cDistance(cSortIdx);
    cidx = cidx(cSortIdx);
    cDistMatrix = abs(cDistance - cDistance');
    for i = 1:length(cDistMatrix)-1
        for j = i+1:length(cDistMatrix)
            if cDistMatrix(i,j) <= distThreshold && (f1spkFullIdx(cidx(i))~=f1spkFullIdx(cidx(j)))
                plot(f1spkFull(cidx(i)),f1spkFull(cidx(j)),'marker','.','color','k','markersize',markerSize,'linewidth',lineWidth);
            end
        end
    end
end
xlim([setBackY(2) 0.4]);
ylim([setBackX(2) 0.35]);
line([0 0.5],setBackX(1)+[0,0],'color','k','linewidth',lineWidth);
line(setBackY(1)+[0 0],[0 0.35],'color','k','linewidth',lineWidth);
xticks = 0:0.2:0.4;%0:100:300;
for xt = xticks
    line(xt+[0,0],setBackX([1 2]),'color','k','linewidth',lineWidth);
    text(xt,setBackX(3),num2str(xt),'fontsize',fontSize,'horizontalalignment','center','verticalAlignment','top');
end
text(0.2,setBackX(4),'S1 \DeltaCa_{AP} (\DeltaG/R)','Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Top');
yticks = 0:0.1:0.3;
for yt = yticks
    line(setBackY([1,2]),yt+[0,0],'color','k','linewidth',lineWidth);
    text(setBackY(3),yt,num2str(yt),'fontsize',fontSize,'horizontalalignment','right');
end
text(setBackY(4),0.35/2,'S2 \DeltaCa_{AP} (\DeltaG/R)','fontsize',fontSize,'HorizontalAlignment','center','verticalAlignment','bottom','Rotation',90);
text(0, 0.31, 'Within-Cell Spine Pairs', 'Fontsize',fontSize, 'HorizontalAlignment','Left');
text(0, 0.28, '\approxsame distance', 'Fontsize',fontSize, 'HorizontalAlignment','Left');
set(gca,'visible','off');









%% -- Figure 2 - Figure Supplement 1


% Figure 2 - figure supplement 1A
setBackX = [-0.015 -0.025 -0.025 -0.068];
setBackY = [-5 -10 -12 -62];
figure(1); clf; 
set(gcf,'units','centimeters','position',[37 30 axWidth(1) axHeight*0.95]);
set(gca,'units','centimeters','position',[0.7 0.6 axWidth(1)*0.76 axHeight*0.82*0.95]);
plot(distance, nlComponent, 'marker','.','color','k','markersize',markerSize,'linestyle','none');
xlim([setBackY(2) 300]);
ylim([setBackX(2) 0.5]);
line([0 300],setBackX(1)+[0,0],'color','k','linewidth',lineWidth);
line(setBackY(1)+[0 0],[0 0.5],'color','k','linewidth',lineWidth);
xticks = 0:100:300;
for xt = xticks
    line(xt+[0,0],setBackX([1 2]),'color','k','linewidth',lineWidth);
    text(xt,setBackX(3),num2str(xt),'fontsize',fontSize,'horizontalalignment','center','verticalAlignment','top');
end
text(150,setBackX(4),'distance from soma (µm)','Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Top');
yticks = 0:0.2:0.4;
for yt = yticks
    line(setBackY([1,2]),yt+[0,0],'color','k','linewidth',lineWidth);
    text(setBackY(3),yt,num2str(yt),'fontsize',fontSize,'horizontalalignment','right');
end
text(setBackY(4),0.25,'Amplification (\DeltaG/R)','fontsize',fontSize,'HorizontalAlignment','center','verticalAlignment','bottom','Rotation',90);
set(gca,'visible','off');



% Figure 2 - figure supplement 1B
setBackX = [-0.015 -0.025 -0.025 -0.068];
setBackY = [-5 -10 -12 -55];
figure(2); clf; 
set(gcf,'units','centimeters','position',[37 20 axWidth(1) axHeight*0.95]);
set(gca,'units','centimeters','position',[0.7 0.6 axWidth(1)*0.76 axHeight*0.82*0.95]);
plot(f1distance, f1dpk, 'marker','.','color','k','markersize',markerSize,'linestyle','none');
xlim([setBackY(2) 300]);
ylim([setBackX(2) 0.5]);
line([0 300],setBackX(1)+[0,0],'color','k','linewidth',lineWidth);
line(setBackY(1)+[0 0],[0 0.5],'color','k','linewidth',lineWidth);
xticks = 0:100:300;
for xt = xticks
    line(xt+[0,0],setBackX([1 2]),'color','k','linewidth',lineWidth);
    text(xt,setBackX(3),num2str(xt),'fontsize',fontSize,'horizontalalignment','center','verticalAlignment','top');
end
text(150,setBackX(4),'distance from soma (µm)','Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Top');
yticks = 0:0.2:0.4;
for yt = yticks
    line(setBackY([1,2]),yt+[0,0],'color','k','linewidth',lineWidth);
    text(setBackY(3),yt,num2str(yt),'fontsize',fontSize,'horizontalalignment','right');
end
text(setBackY(4),0.25,'\DeltaCa_{AP} (\DeltaG/R)','fontsize',fontSize,'HorizontalAlignment','center','verticalAlignment','bottom','Rotation',90);
set(gca,'visible','off');




% Figure 2 - figure supplement 1C
setBackX = [-0.025 -0.038 -0.035 -0.09]*10;
setBackY = [-0.025 -0.038 -0.045 -0.195];
figure(3); clf; hold on;
set(gcf,'units','centimeters','position',[41 30 axWidth(1) axHeight]);
set(gca,'units','centimeters','position',[0.75 0.7 axWidth(1)*0.75 axWidth(1)*0.75]); % Note difference for equal axes!
plot(spk(:,1),ampreglu,'linestyle','none','marker','.','markersize',markerSize,'color','k');
line([0 0.5],setBackX(1)*[1,1],'color','k','linewidth',lineWidth);
line(setBackY(1)*[1,1],[0 5],'color','k','linewidth',lineWidth);
xticks = 0:0.2:0.4;
for t = xticks
    line(t+[0,0],setBackX([1 2]),'color','k','linewidth',lineWidth);
    text(t,setBackX(3),num2str(t),'fontsize',fontSize,'horizontalalignment','center','verticalAlignment','top');
end
yticks = 0:2:4;
for t = yticks
    line(setBackY([1 2]),t+[0,0],'color','k','linewidth',lineWidth);
    text(setBackY(3),t,num2str(t),'fontsize',fontSize,'horizontalalignment','right','verticalAlignment','Middle');
end
xlim([setBackY(2) 0.5]);
ylim([setBackX(2) 5]);
text(0.25,setBackX(4),'\DeltaCa_{AP} (\DeltaG/R)','fontsize',fontSize,'HorizontalAlignment','center','verticalAlignment','top');
text(setBackY(4),2.5,'\DeltaCa_{amp}/\DeltaCa_{EPSP}','fontsize',fontSize,'HorizontalAlignment','center','verticalAlignment','top','Rotation',90);
set(gca,'visible','off');





pgluBase = smoothsmooth(medfilt1(pglu - repmat(mean(pglu(850:999,:),1),length(ptv),1),5),10);
[epspPk,epspPt] = max(pgluBase(1000:1250,:),[],1);
epspPt = epspPt + 1000 - 1;
epspTime = ptv(epspPt);


% Figure 2 - figure supplement 1D
figure(4); clf; hold on;
set(gcf,'units','centimeters','position',[41 20 axWidth(1) axHeight]);
set(gca,'units','centimeters','position',[0.3 0.15 axWidth(1)*0.825 axWidth(1)*1]); % Note difference for equal axes!
shadedErrorBar(ptv, mean(pgluBase(:,idxActive),2),std(pgluBase(:,idxActive),1,2)/sqrt(sum(idxActive)),{'color','k','linewidth',lineWidth},1);
shadedErrorBar(ptv, mean(pgluBase(:,idxSilent),2),std(pgluBase(:,idxSilent),1,2)/sqrt(sum(idxSilent)),{'color','b','linewidth',lineWidth},1);
xlim([90 180]);
ylim([-0.04 0.45]);
line([100,100],[-0.04 -0.02],'color','k','linewidth',lineWidth);
% Make Legend
legPos = [155 0.175 20 0.05];
line(legPos(1) + [0 legPos(3)],legPos([2,2]),'color','k','linewidth',lineWidth);
line(legPos([1,1]),legPos(2) + [0 legPos(4)],'color','k','linewidth',lineWidth);
text(legPos(1),legPos(2),sprintf('%d ms',legPos(3)),'FontSize',fontSize,'horizontalAlignment','Left','VerticalAlignment','Top');
text(legPos(1),legPos(2),sprintf('%.1f mV',legPos(4)),'FontSize',fontSize,'horizontalAlignment','Left','VerticalAlignment','Bottom','Rotation',90);
% Make Label
labelPos = [180 -8 -3 0.4 -0.05];
line(labelPos(1) + [0 labelPos(2)],labelPos(4)*[1,1],'color','k','linewidth',lineWidth);
line(labelPos(1) + [0 labelPos(2)],(labelPos(4)+labelPos(5))*[1,1],'color','b','linewidth',lineWidth);
text(sum(labelPos(1:3)),labelPos(4) + 0*labelPos(5), 'High \DeltaCa_{AP}','Fontsize',fontSize,'HorizontalAlignment','Right');
text(sum(labelPos(1:3)),labelPos(4) + 1*labelPos(5), 'Low \DeltaCa_{AP}','Fontsize',fontSize,'HorizontalAlignment','Right');
set(gca,'visible','off');
% print(gcf,'-painters',fullfile(figureSizePath,'SFig2B_epspTraces'),'-depsc');



setBackX = [-0.025 -0.038 -0.035 -0.09]*2.2;
setBackY = [-0.025 -0.038 -0.045 -0.13];
% Figure 2 - figure supplement 1E
figure(5); clf; hold on;
set(gcf,'units','centimeters','position',[45 30 axWidth(1) axHeight]);
set(gca,'units','centimeters','position',[0.75 0.7 axWidth(1)*0.725 axHeight(1)*0.75]); % Note difference for equal axes!
patch([0 0.04 0.04 0],[0 0 1.2 1.2],[0.5 0.5 1],'EdgeColor','none');
patch([0.1 0.3 0.3 0.1],[0 0 1.2 1.2],[0.5 0.5 0.5],'EdgeColor','none');
plot(spk(:,1), epspPk, 'color','k','marker','.','markersize',markerSize,'linestyle','none');
line([0 0.5],setBackX(1)*[1,1],'color','k','linewidth',lineWidth);
line(setBackY(1)*[1,1],[0 1.2],'color','k','linewidth',lineWidth);
xticks = 0:0.2:0.4;
for t = xticks
    line(t+[0,0],setBackX([1 2]),'color','k','linewidth',lineWidth);
    text(t,setBackX(3),num2str(t),'fontsize',fontSize,'horizontalalignment','center','verticalAlignment','top');
end
yticks = 0:0.5:1;
for t = yticks
    line(setBackY([1 2]),t+[0,0],'color','k','linewidth',lineWidth);
    text(setBackY(3),t,num2str(t),'fontsize',fontSize,'horizontalalignment','right','verticalAlignment','Middle');
end
xlim([setBackY(2) 0.5]);
ylim([setBackX(2) 1.2]);
text(0.25,setBackX(4),'\DeltaCa_{AP} (\DeltaG/R)','fontsize',fontSize,'HorizontalAlignment','center','verticalAlignment','top');
text(setBackY(4),0.6,'EPSP Amplitude (mV)','fontsize',fontSize,'HorizontalAlignment','center','verticalAlignment','Bottom','Rotation',90);
set(gca,'visible','off');

% Figure 2 - figure supplement 1F
setBackX = [-0.025 -0.038 -0.035 -0.09]*60;
setBackY = [-0.025 -0.038 -0.045 -0.13];
figure(6); clf; hold on;
set(gcf,'units','centimeters','position',[45 20 axWidth(1) axHeight]);
set(gca,'units','centimeters','position',[0.75 0.7 axWidth(1)*0.725 axHeight(1)*0.75]); % Note difference for equal axes!
patch([0 0.04 0.04 0],[0 0 30 30],[0.5 0.5 1],'EdgeColor','none');
patch([0.1 0.3 0.3 0.1],[0 0 30 30],[0.5 0.5 0.5],'EdgeColor','none');
plot(spk(:,1), epspTime-100, 'color','k','marker','.','markersize',markerSize,'linestyle','none');
line([0 0.5],setBackX(1)*[1,1],'color','k','linewidth',lineWidth);
line(setBackY(1)*[1,1],[0 30],'color','k','linewidth',lineWidth);
xticks = 0:0.2:0.4;
for t = xticks
    line(t+[0,0],setBackX([1 2]),'color','k','linewidth',lineWidth);
    text(t,setBackX(3),num2str(t),'fontsize',fontSize,'horizontalalignment','center','verticalAlignment','top');
end
yticks = 0:10:30;
for t = yticks
    line(setBackY([1 2]),t+[0,0],'color','k','linewidth',lineWidth);
    text(setBackY(3),t,num2str(t),'fontsize',fontSize,'horizontalalignment','right','verticalAlignment','Middle');
end
xlim([setBackY(2) 0.5]);
ylim([setBackX(2) 30]);
text(0.25,setBackX(4),'\DeltaCa_{AP} (\DeltaG/R)','fontsize',fontSize,'HorizontalAlignment','center','verticalAlignment','top');
text(setBackY(4),15,'EPSP Peak Time (ms)','fontsize',fontSize,'HorizontalAlignment','center','verticalAlignment','Bottom','Rotation',90);
set(gca,'visible','off');


% Figure 2 - figure supplement 1G
setBackX = [-0.025 -0.038 -0.035 -0.09]*2.2;
setBackY = [-0.025 -0.038 -0.045 -0.13]/0.5*300;
figure(7); clf; hold on;
set(gcf,'units','centimeters','position',[49 30 axWidth(1) axHeight]);
set(gca,'units','centimeters','position',[0.75 0.7 axWidth(1)*0.725 axHeight(1)*0.75]); % Note difference for equal axes!
plot(distance, epspPk, 'color','k','marker','.','markersize',markerSize,'linestyle','none');
line([0 300],setBackX(1)*[1,1],'color','k','linewidth',lineWidth);
line(setBackY(1)*[1,1],[0 1.2],'color','k','linewidth',lineWidth);
xticks = 0:100:300;
for t = xticks
    line(t+[0,0],setBackX([1 2]),'color','k','linewidth',lineWidth);
    text(t,setBackX(3),num2str(t),'fontsize',fontSize,'horizontalalignment','center','verticalAlignment','top');
end
yticks = 0:0.5:1;
for t = yticks
    line(setBackY([1 2]),t+[0,0],'color','k','linewidth',lineWidth);
    text(setBackY(3),t,num2str(t),'fontsize',fontSize,'horizontalalignment','right','verticalAlignment','Middle');
end
xlim([setBackY(2) 300]);
ylim([setBackX(2) 1.2]);
text(150,setBackX(4),'Distance (µm)','fontsize',fontSize,'HorizontalAlignment','center','verticalAlignment','top');
text(setBackY(4),0.6,'EPSP Amplitude (mV)','fontsize',fontSize,'HorizontalAlignment','center','verticalAlignment','Bottom','Rotation',90);
set(gca,'visible','off');

% Figure 2 - figure supplement 1H
setBackX = [-0.025 -0.038 -0.035 -0.09]*60;
setBackY = [-0.025 -0.038 -0.045 -0.13]/0.5*300;
figure(8); clf; hold on;
set(gcf,'units','centimeters','position',[49 20 axWidth(1) axHeight]);
set(gca,'units','centimeters','position',[0.75 0.7 axWidth(1)*0.725 axHeight(1)*0.75]); % Note difference for equal axes!
plot(distance, epspTime-100, 'color','k','marker','.','markersize',markerSize,'linestyle','none');
line([0 300],setBackX(1)*[1,1],'color','k','linewidth',lineWidth);
line(setBackY(1)*[1,1],[0 30],'color','k','linewidth',lineWidth);
xticks = 0:100:300;
for t = xticks
   line(t+[0,0],setBackX([1 2]),'color','k','linewidth',lineWidth);
   text(t,setBackX(3),num2str(t),'fontsize',fontSize,'horizontalalignment','center','verticalAlignment','top');
end
yticks = 0:10:30;
for t = yticks
    line(setBackY([1 2]),t+[0,0],'color','k','linewidth',lineWidth);
    text(setBackY(3),t,num2str(t),'fontsize',fontSize,'horizontalalignment','right','verticalAlignment','Middle');
end
xlim([setBackY(2) 300]);
ylim([setBackX(2) 30]);
text(150,setBackX(4),'Distance (µm)','fontsize',fontSize,'HorizontalAlignment','center','verticalAlignment','top');
text(setBackY(4),15,'EPSP Peak Time (ms)','fontsize',fontSize,'HorizontalAlignment','center','verticalAlignment','Bottom','Rotation',90);
set(gca,'visible','off');





